package top.lanscarlos.ashcraft.utils;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Ashcraft
 * top.lanscarlos.ashcraft.utils
 *
 * @author Lanscarlos
 * @since 2022-05-25 15:11
 */
public class DigestUtil {

    /**
     * 使用 md5 算法加密字符串
     *
     * @param source 源字符串
     * */
    public static String digest(String source) {
        return digest(source, "md5");
    }

    /**
     * 加密字符串
     *
     * @param source 源字符串
     * @param algorithm 算法类型（可使用 md5、sha-1、sha-256 等）
     * */
    public static String digest(String source, String algorithm) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            digest.update(source.getBytes(StandardCharsets.UTF_8));
            return new BigInteger(1, digest.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("No such algorithm name \"" + algorithm + "\"");
        }
    }

}
